package com.lxiaodd.handler;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 请求数据代理类
 * @author liupeng
 *
 */
public class MyRequestWrapper extends HttpServletRequestWrapper {
	private String requestBodyStr = null;//参数字符串
	private Map<String, String[]> parameterMap; // 所有参数的Map集合 form提交
 
	public MyRequestWrapper(HttpServletRequest request) {
		super(request);
		if (requestBodyStr == null) {
			requestBodyStr = readBody(request);
		}
	}
 
	/*----------------json处理 begin----------------------*/
	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}
 
	@Override
	public ServletInputStream getInputStream() throws IOException {
		return new CustomServletInputStream(requestBodyStr);
	}
 
	private static String readBody(ServletRequest request) {
		StringBuilder sb = new StringBuilder();
		String inputLine;
		BufferedReader br = null;
		try {
			br = request.getReader();
			while ((inputLine = br.readLine()) != null) {
				sb.append(inputLine);
			}
		} catch (IOException e) {
			throw new RuntimeException("Failed to read body.", e);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
		return sb.toString();
	}
 
	private class CustomServletInputStream extends ServletInputStream {
		private ByteArrayInputStream buffer;
 
		public CustomServletInputStream(String body) {
			body = body == null ? "" : body;
			try {
				this.buffer = new ByteArrayInputStream(body.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				this.buffer = new ByteArrayInputStream(body.getBytes());
			}
		}
 
		@Override
		public int read() throws IOException {
			return buffer.read();
		}
 
		@Override
		public boolean isFinished() {
			return buffer.available() == 0;
		}
 
		@Override
		public boolean isReady() {
			return true;
		}
 
		@Override
		public void setReadListener(ReadListener listener) {
			throw new RuntimeException("Not implemented");
		}
	}

	public String getRequestBodyStr() {
		return requestBodyStr;
	}

	public void setRequestBodyStr(String requestBodyStr) {
		this.requestBodyStr = requestBodyStr;
	}
	/*----------------json处理 end----------------------*/
	
	/*----------------parameter 处理 begin----------------------*/
	/**
     * 获取所有参数名
     * 
     * @return 返回所有参数名
     */
    @Override
    public Enumeration<String> getParameterNames() {
        Vector<String> vector = new Vector<String>(parameterMap.keySet());
        return vector.elements();
    }
    
    /**
     * 获取指定参数名的值，如果有重复的参数名，则返回第一个的值 接收一般变量 ，如text类型
     * 
     * @param name
     *            指定参数名
     * @return 指定参数名的值
     */
    @Override
    public String getParameter(String name) {
    	 Object v = parameterMap.get(name);
         if (v == null) {
             return null;
         } else if (v instanceof String[]) { //一个name可能对应多个value， 返回第一个
             String[] strArr = (String[]) v;
             if (strArr.length > 0) {
                 return strArr[0]; 
             } else {
                 return null;
             }
         } else if (v instanceof String) {
             return (String) v;
         } else {
             return v.toString();
         }
    }
    
    /**
     * 获取指定参数名的所有值的数组，如：checkbox的所有数据 
     * 接收数组变量 ，如checkobx类型
     */
    @Override
    public String[] getParameterValues(String name) {
    	 Object v = parameterMap.get(name);
         if (v == null) {
             return null;
         } else if (v instanceof String[]) {
             return (String[]) v;
         } else if (v instanceof String) {
             return new String[] { (String) v };
         } else {
             return new String[] { v.toString() };
         }
    }

	public Map<String, String[]> getParameterMap() {
		return parameterMap;
	}

	public void setParameterStr(String parameterStr) {
		this.parameterMap = new HashMap<String, String[]>();
        String[] paramFlex = parameterStr.split("&"); //通过&进行分割
        for (String s : paramFlex) {
            String[] pairparam = s.split("=");
            if (pairparam.length > 1) {
            	parameterMap.put(pairparam[0], new String[]{pairparam[1]});
            }
        }
	}

    
	/*----------------parameter 处理 end----------------------*/

	
}
